﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace GeoCoderParser
{
    class Doorplate
    {
        public int major;
        public int mid;
        public int minor;

        public Doorplate()
        {
            major = 0;
            mid = 0;
            minor = 0;
        }

        public int DistanceTo(Doorplate dp)
        {
            int distance = 0;
            distance = Math.Abs(major - dp.major) * 1000000 + Math.Abs(mid - dp.mid) * 1000 + Math.Abs(minor - dp.minor);

            int flag = (major - dp.major) * 1000000 + (mid - dp.mid) * 1000 + (minor - dp.minor);
            if (flag > 0)
            {
                return distance;
            }
            else
            {
                return -1 * distance;
            }
        }
    }

    class DoorplateExtractor
    {
        private string strExtractorPattern = "[#]?([A-Za-z甲乙丙丁戊己庚辛壬癸\\-－负副辅+＋正之]?[一二三四五六七八九万千百十〇零0123456789]+[A-Za-z甲乙丙丁戊己庚辛壬癸]?)";
        private Regex regex;

        public DoorplateExtractor()
        {
            regex = new Regex(strExtractorPattern);
        }

        public Doorplate Extract(string strDoorplate)
        {
            bool bFirst = true;
            List<string> rstList = new List<string>();
            Match m = regex.Match(strDoorplate);
            while (m.Success == true)
            {
                if (bFirst == true)
                {
                    if (m.Index >= 2)
                    {
                        return null;
                    }
                    bFirst = false;
                }

                rstList.Add(m.Groups[1].ToString());
                m = m.NextMatch();
            }

            Doorplate dp = new Doorplate();
            List<int> iDoorplateList = new List<int>();
            for (int i = 0; i < rstList.Count && iDoorplateList.Count < 3; i++)
            {
                int n;
                bool bRet = int.TryParse(rstList[i], out n);
                if (bRet == true)
                {
                    iDoorplateList.Add(n);
                }
            }

            for (int i = 0; i < iDoorplateList.Count && i < 3; i++)
            {
                if (i == 0)
                {
                    dp.major = iDoorplateList[i];
                }
                else if (i == 1)
                {
                    dp.mid = iDoorplateList[i];
                }
                else if (i == 2)
                {
                    dp.minor = iDoorplateList[i];
                }
            }

            return dp;
        }
    }
}
